package cn.gson.crm.control.interview;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import com.alibaba.fastjson.JSON;

import cn.gson.crm.control.base.BaseServlet;
import cn.gson.crm.model.dao.FileDao;
import cn.gson.crm.model.dao.InterviewDao;
import cn.gson.crm.model.entity.Files;
import cn.gson.crm.model.entity.InterViewVo;
import cn.gson.crm.model.entity.Interview;

/**
 * Servlet implementation class InterViewServlet
 */
@WebServlet("/interview")
public class InterViewServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private InterviewDao view=new InterviewDao();
	private FileDao file=new FileDao();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public InterViewServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void get(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String method=request.getParameter("method");
		if("insert".equalsIgnoreCase(method)){
    			insert(request,response);
		}
		if("select".equalsIgnoreCase(method)){
			select(request,response);
		}
		if("upload".equalsIgnoreCase(method)){
			upload(request,response);
		}
	}
				
private void upload(HttpServletRequest request, HttpServletResponse response) {
		// 判断是否是上传文件的请求类型
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);

		if (isMultipart) {
			try {
				Files f = new Files();
				// 通过这种方式，是获取不到表单的提交值
				// String userName = request.getParameter("userName");
				// System.out.println(userName);

				DiskFileItemFactory factory = new DiskFileItemFactory();
				// 设置单次请求文件的大小
				// factory.setSizeThreshold(1024 * 1024);
				// 创建一个上传文件处理器
				ServletFileUpload upload = new ServletFileUpload(factory);
				// 设置每一个文件的最大大小
				// upload.setFileSizeMax(1024 * 1024);

				// 解析request
				List<FileItem> fileItems = upload.parseRequest(request);
				for (FileItem fileItem : fileItems) {
					// 获取表单的name值
					String fieldName = fileItem.getFieldName();
					// 表单的字段值
					InputStream stream = fileItem.getInputStream();
					if (fileItem.isFormField()) {
						// 表示当前这个item是一个普通表单字段
						String value = Streams.asString(stream);
						//System.out.println("表单名称：" + fieldName + ",表单值是：" + value);
						f.setModel(value);
					} else {
						// 表示这个item是一个文件字段
						// 获取服务器的运行根目录
						String rootPath = request.getServletContext().getRealPath("/");

						// 创建文件上传的根目录
						File uploadDir = new File(rootPath, "upload");
						// 判断上传目录是否存在，不存在就创建
						if (!uploadDir.exists()) {
							uploadDir.mkdirs();
						}
						// 获取文件的原始名称xxxx.jpg
						String fileName = fileItem.getName();
						// 获取文件的后缀
						String suffix = fileName.substring(fileName.lastIndexOf("."));
						// 使用uuid生成新的文件名称
						String uuid = UUID.randomUUID().toString();
						File file = new File(uploadDir, uuid + suffix);

						// 将fileItem里面的inputStram写入file文件中。
						fileItem.write(file);

						f.setFileName(fileName);
						f.setFilePath("upload/" + uuid + suffix);
						f.setFileSize(file.length());
					}
				}
				// 存储附件信息
				Long attId = file.savFile(f);
				if (attId != null) {
					f.setId(attId);
					response.getWriter().append(JSON.toJSONString(f));
				} else {
					response.getWriter().append("{\"message\":\"附件上传失败！\"}");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	
	}

	private void select(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String name=request.getParameter("name");
		String id=request.getParameter("viewid");
		List<InterViewVo> list=view.geteInterviewById(id);
		InterViewVo listview=view.geteInterviewByname(name);
		request.setAttribute("listview", listview);
		request.setAttribute("list", list);
		request.setAttribute("name", name);
		forward("interview/interviewchakan.jsp");
	}
	private void insert(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String company=request.getParameter("company");
		String address=request.getParameter("address");
		String zongjie=request.getParameter("zongjie");
		String id=request.getParameter("stuid");
		Interview inter=new Interview();
		inter.setInterviewCompany(company);
		inter.setInterviewAddress(address);
		inter.setInterviewStudentId(Integer.parseInt(id));
		inter.setInterviewSummary(zongjie);
		String[] attchs = request.getParameterValues("attachs");
		Long mianShiId=new InterviewDao().insertInterview(inter);
	 	//如果mianShiId不为空则表示面试记录插入成功
	 	if(mianShiId != null){
	 		//有附件就关联附件信息
	 		//严格意义来说，这里是要做事务控制
	 		if(attchs!=null && attchs.length > 0){
	 			file.guanLian(mianShiId,attchs);
	 		}
	 	}
		redirect("student?method=selectgroup");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void post(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		get(request, response);
		}

}
